<?php
// 测试API接口的简单脚本

// 引入ThinkPHP框架
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../app/model/User.php';
require __DIR__ . '/../app/controller/WechatController.php';

use app\model\User;
use app\controller\WechatController;
use think\facade\Db;

// 设置响应头为JSON
header('Content-Type: application/json; charset=utf-8');

try {
    // 模拟创建一个测试用户
    $user = [
        'openid' => 'test_openid_' . time(),
        'nickname' => '测试用户',
        'avatar' => 'https://example.com/avatar.jpg',
        'gender' => 1,
        'city' => '北京',
        'agent_level' => 1,
        'status' => 1,
    ];
    
    // 检查用户是否已存在
    $existUser = User::where('openid', $user['openid'])->find();
    if (!$existUser) {
        // 创建用户
        $userModel = User::create($user);
        echo json_encode([
            'code' => 0,
            'message' => '测试用户创建成功',
            'data' => [
                'user_id' => $userModel->id,
                'openid' => $userModel->openid
            ]
        ], JSON_UNESCAPED_UNICODE);
    } else {
        $userModel = $existUser;
        echo json_encode([
            'code' => 0,
            'message' => '测试用户已存在',
            'data' => [
                'user_id' => $userModel->id,
                'openid' => $userModel->openid
            ]
        ], JSON_UNESCAPED_UNICODE);
    }
    
    // 生成token
    $wechatController = new WechatController(app());
    $token = 'Bearer ' . base64_encode(json_encode([
        'openid' => $userModel->openid,
        'id' => $userModel->id,
        'time' => time()
    ]));
    
    echo "\n\n";
    echo json_encode([
        'code' => 0,
        'message' => '测试Token生成成功',
        'data' => [
            'token' => $token,
            'user_id' => $userModel->id
        ]
    ], JSON_UNESCAPED_UNICODE);
    
    echo "\n\n";
    echo "使用方法：\n";
    echo "1. 复制上面生成的token\n";
    echo "2. 在API请求中添加Header: 'Authorization: " . $token . "'\n";
    echo "3. 现在可以测试需要登录的API接口了\n";
    
    echo "\n\n";
    echo "测试接口示例：\n";
    echo "1. 获取用户信息: GET /api/user/info\n";
    echo "2. 提交纸条: POST /api/note/submit\n";
    echo "3. 抽取纸条: POST /api/note/draw\n";
    echo "4. 获取系统设置: GET /api/system/settings\n";
    
} catch (Exception $e) {
    echo json_encode([
        'code' => 1,
        'message' => '测试出错: ' . $e->getMessage(),
        'data' => null
    ], JSON_UNESCAPED_UNICODE);
} 